

// 引入路径处理模块
let path = require('path');
const util = require('../utils/index')
const express = require('express')
// 创建路由对象
const router = express.Router()
const db = require("../db")

// 注册用户
// TODO
router.post('/register', (request, response) => {
  let name = request.body.name
  let password = request.body.password
  if (!name || name.length <= 3) {
    response.send({
      code: 400,
      message: "用户名过短",
      data: {}
    })
    return
  }
  if (!password || password.length < 8) {
    response.send({
      code: 400,
      message: "密码过短",
      data: {}
    })
    return
  }

  let sql = db.getUserDetailByName(name)
  db.Query(sql).then(res => {
    if (res.length === 0) {
      //没有相同的人物，可以注册
      //对密码进行加密
      password = util.encrypt(name, password);
      let sql = db.regNewUser(name, password)

      db.Query(sql).then(res => {
        if (res.affectedRows === 1) {
          response.send({
            code: 200,
            message: "注册成功",
            data: {}
          })
        } else {
          return Promise.reject("出现未知错误，联系管理员")
        }
      }).catch(err => Promise.reject(err))

    } else {
      //存在相同人名，返回
      return Promise.reject("用户名已注册，请重新输入")
    }
  }).catch(err => {
    response.send({
      code: 400,
      message: err,
      data: {}
    })
  })
})

//添加图片
router.post("/changeAvatar", util.upload.single("file"), (req, res) => {
  //接收上传文件数据 
  if (req.file) {
    let imgpath = "/uploads/"+req.file.filename;
    let id=req.auth.id
    let sql = db.changeUserAvatar(id, imgpath);
    db.Query(sql).then(data => {
      if(data.affectedRows===1){
        res.send({
          code:200,
          message:"头像更新成功！",
          data:{imgpath}
        })
      }else{
        return Promise.reject("error")
      }
    }).catch(err=>{
      res.send({
        code:400,
        message:err,
        data:{}
      })
    });
  } else {
    res.send({
      code: 400,
      message: "错误，未上传图片",
      data: {}
    })
  }
})

//更改个人密码
router.post('/changePassword', (req, res) => {
  let name = req.auth.name
  let id = req.auth.id
  console.log(id)

  let password = req.body.password;
  let newPassword = req.body.newPassword;

  if (password.length < 8 || newPassword.length < 8) {
    res.send({
      code: 400,
      message: "密码过短！",
      data: {}
    })
    return
  }

  let sql = db.getUserDetailByName(name);
  db.Query(sql).then(data => {
    if (data.length === 1) {
      //存在用户
      //对密码进行加密
      password = util.encrypt(name, password);
      let dbPassword = data[0].password
      if (password === dbPassword) {
        newPassword = util.encrypt(name, newPassword);
        sql = db.changeUserPassword(id, newPassword)
        db.Query(sql).then(data => {
          res.send({
            code: 200,
            message: "修改密码成功",
            data: {}
          })
        }).catch(err => Promise.reject(err))
      } else {
        return Promise.reject("密码错误，请检查")
      }
    } else {
      return Promise.reject("未知错误")
    }
  }).catch(err => {
    res.send({
      code: 400,
      message: err,
      data: {}
    })
  });
});

//登录路由
router.post('/login', (request, response) => {
  // console.log("enter",request.body)
  let name = request.body.name
  let password = request.body.password
  let sql = db.getUserDetailByName(name)
  db.Query(sql).then(res => {
    // console.log(res)
    if (res.length === 1) {
      //存在用户
      //对密码进行加密
      password = util.encrypt(name, password);
      let dbPassword = res[0].password
      if (password === dbPassword) {
        //生成一个token
        let token = "Bearer " + util.encodeJwt({ id: res[0].id, name, type: res[0].type });
        response.send({
          code: 200,
          message: "登录成功",
          data: {
            token
          }
        })
      } else {
        return Promise.reject()
      }
    } else {
      //不存在相同人名，返回
      return Promise.reject("登录失败，请检查用户名密码相关信息！")
    }
  }).catch(err => {
    response.send({
      code: 400,
      message: "登录失败，请检查用户名或密码",
      data: {}
    })
  })
});

//检查登录信息，返回相关信息
router.post('/checkLogin',(req,res)=>{
  console.log("checklogin")
  res.send({
    code:200,
    message:"登录未过期",
    data:{
      name:req.auth.name
    }
  })
})

//获取用户信息
router.post('/getUserInfo',(req,res)=>{
  console.log(req.auth)
  let name = req.auth.name

  let sql = db.getUserDetailByName(name)
  db.Query(sql).then(data => {
    if(data.length===1){
      let user=data[0]
      console.log(data)
      res.send({
        code:200,
        message:"查询成功",
        data:{
          id:user.id,
          name:user.name,
          imgpath:user.imgpath,
          type:user.type,
          regdate:user.regdate
        }
      })
    }else{
      res.send({
        code:400,
        message:"没有相关信息",
      })
    }
  })
})

// 将路由对象共享出去
module.exports = router